package com.jlnk.stockdemo.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jlnk.stockdemo.R;
import com.jlnk.stockdemo.adapter.FutureAdapter;
import com.jlnk.stockdemo.bean.FutureListResponse;
import com.jlnk.stockdemo.viewmodel.FutureViewModel;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class FuturesFragment extends Fragment {
    private static final String TAG = "FuturesFragment";
    private FutureViewModel futureViewModel;
    private RecyclerView recyclerview_future;
    private FutureAdapter futureAdapter;
    private List<FutureListResponse.Data.Future> futureList = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_futures, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        futureAdapter = new FutureAdapter(futureList);
        recyclerview_future = view.findViewById(R.id.recyclerview_future);
        recyclerview_future.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerview_future.setAdapter(futureAdapter);

        futureViewModel = new ViewModelProvider(this).get(FutureViewModel.class);
        futureViewModel.getFutureListLiveData().observe(getViewLifecycleOwner(), futures -> {
            this.futureList.clear();
            this.futureList.addAll(futures);
            futureAdapter.notifyDataSetChanged();
        });
        futureViewModel.fetchFutureList();
    }
}
